package com.github.baichuan.web.dto;

import com.github.baichuan.mapping.BeanMapper;
import jakarta.validation.Valid;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.Arrays;
import java.util.Set;

/**
 * 分页查询请求
 * @param <T> 查询条件对象类型
 */
@Setter
@Getter
@NoArgsConstructor
@Slf4j
public class PaginationCriteria<T> {
    /**
     * 页编码(从1开始)
     */
    private int pageIndex = 1;

    /**
     * 每页数据条数
     */
    private int pageSize = 10;

    @Valid
    private T criteria;

    /**
     * 返回数据的属性
     */
    private Set<String> properties;

    private OrderBy order;

    public PaginationCriteria(int pageIndex, int pageSize, T criteria){
        this.pageIndex = pageIndex;
        this.pageSize = pageSize;
        this.criteria = criteria;
    }

    public PaginationCriteria(int pageIndex, int pageSize, T criteria, OrderBy order){
        this.pageIndex = pageIndex;
        this.pageSize = pageSize;
        this.order = order;
        this.criteria = criteria;
    }

    public Pageable pageable(){
        return PageRequest.of(pageIndex - 1, pageSize);
    }

    public Pageable pageable(Class<?> clazz) {
        Sort.Direction direction = this.order.getDirection();

        String sortProperty = this.order.getProperty();
        try {
            if(clazz.getDeclaredField(sortProperty) != null){
                sortProperty = BeanMapper.getMappingValue(clazz, sortProperty);
            }
        } catch (NoSuchFieldException ex) {
            log.error("NoSuchFieldException:{}", sortProperty);
            throw new RuntimeException(sortProperty + "不存在", ex);
        }

        if(!this.order.getProperty().equals("id")
                && Arrays.stream(clazz.getDeclaredFields()).anyMatch(f -> f.getName().equals("id"))) {
            return PageRequest.of(pageIndex - 1, pageSize, direction, sortProperty, "id");
        }
        else{
            return PageRequest.of(pageIndex - 1, pageSize, direction, sortProperty);
        }

    }
}
